//
//  ViewController.swift
//  SmallParts
//
//  Created by 航汇聚 on 2019/10/8.
//  Copyright © 2019 BellaZhou. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var bannerContentView: UIView!
    @IBOutlet weak var headerView: UIView!
    @IBOutlet weak var titleView: TitleView!
    let manager = URLManager.sharedURLManager
    let upload = UploadingData.sharedUploadingData
    let loopView = HorizontalScrollView.loadLoopView()
    var articalGuessFavoriteList: [GuessFavoriteListItem]?
    var mediaGuessFavoriteList: [GuessFavoriteMediaListItem]?
    override func viewDidLoad() {
        loopView.frame = self.bannerContentView.bounds
        self.bannerContentView.addSubview(loopView)
        requestData()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        self.titleView.titleLabel.text = "期刊推荐"
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        loopView.invalidTimer()
    }
}
extension ViewController {
    func requestData() {
        upload.uploadData("\(interfaceHostURL)\(interfacePath)\(getapiticket)", "key=FB1619879B795084B042060E2909037A&outId=110014&userid=0", .post)
        upload.uploadData("\(imHostURL)\(imPath)\(getAppBannerMsg)", "siteId=14", RequestMethod.post)
        upload.success = { (data, urlString) -> () in
            if String(urlString).contains(getAppBannerMsg) {
                let result = try? JSONDecoder().decode([BannerMsg].self, from: data!)
                if let result = result {
                    self.loopView.bannerMsgObjs = result
                    self.loopView.setImageForLoop()
                    self.loopView.autoScrollByDuration(3)
                }
            }
            if String(urlString).contains(getapiticket) {
                //print("getapiticket: \(String(data: data!, encoding: .utf8))")
            }
        }
        manager.startLoad("\(apiHostURL)\(apiPath)\(GuessFavoriteMedia)")
        manager.startLoad("\(apiHostURL)\(apiPath)\(GuessFavorite)")
        manager.success = { (data, urlString) -> () in
            if String(urlString).contains(GuessFavorite) {
                let result = try? JSONDecoder().decode(GuessFavoriteResponseDict.self, from: data!)
                self.articalGuessFavoriteList = (result?.result?.list)!
                self.tableView.reloadData()
            }
            if String(urlString).contains(GuessFavoriteMedia) {
                let result = try? JSONDecoder().decode(GuessFavoriteMediaResponseDict.self, from: data!)
                self.mediaGuessFavoriteList = (result?.result?.list)!
                self.collectionView.reloadData()
            }
        }
    }
}
extension ViewController: UITableViewDataSource,UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.articalGuessFavoriteList?.count ?? 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "articalCell", for: indexPath) as! ArticalCell
        let articalObj = self.articalGuessFavoriteList?[indexPath.row]
        cell.titleLabel?.text = articalObj?.title_c
        cell.writerLabel?.text = "作者:"+(articalObj?.writers)!
        cell.keywordLabel?.text = "关键词:"+(articalObj?.keyword_c)!
        return cell
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 54))
        let titleView = TitleView.init(frame:  CGRect(x: 10, y: 10, width: tableView.bounds.size.width, height: 44))
        titleView.titleLabel.text = "文章推荐"
        header.addSubview(titleView)
        return header
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 54
    }
}
extension ViewController {
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toArticalInfoController" {
            let articalInfoController = segue.destination as! ArticalInfoController
            let indexPath = self.tableView.indexPath(for: sender as! UITableViewCell)! as NSIndexPath
            let articalObj = self.articalGuessFavoriteList?[indexPath.row]
            upload.uploadData("\(apiHostURL)\(apiPath)\(GetInfoNew)", "key=\((articalObj?._id)!)&type=article", .post)
            upload.success = { (data, urlStr) in
                let result = try? JSONDecoder().decode(GetInfoDictArticalModel.self, from: data!)
                articalInfoController.articalInfoObj = result!.result.obj
            }
            articalInfoController.view.backgroundColor = UIColor.white
            articalInfoController.hidesBottomBarWhenPushed = true
        }
        if segue.identifier == "toMediaInfoController" {
            let destionation = segue.destination as! MediaInfoController
            let indexPath = self.collectionView.indexPath(for: sender as! UICollectionViewCell)! as NSIndexPath
            let mediaObj = self.mediaGuessFavoriteList?[indexPath.item]
            upload.uploadData("\(apiHostURL)\(apiPath)\(GetInfoNew)", "key=\((mediaObj?.gch)!)&type=media", .post)
            upload.success = { (data, urlStr) in
                let result = try? JSONDecoder().decode(GetInfoDictMediaModel.self, from: data!)
                destionation.mediaResultObj = result?.result!
            }
            destionation.view.backgroundColor = UIColor.white
            destionation.hidesBottomBarWhenPushed = true
        }
    }
}
class ArticalCell: UITableViewCell {
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var writerLabel: UILabel!
    @IBOutlet weak var keywordLabel: UILabel!
}
extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        self.mediaGuessFavoriteList?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "mediaCollectionCell", for: indexPath) as! MediaCollectionCell
        let mediaObj = self.mediaGuessFavoriteList?[indexPath.item]
        cell.titleLabel.text = mediaObj?.media
        DispatchQueue.global().sync {
            let imgURL = mediaObj?.mediapic
            if (imgURL != nil) {
                let downloadTask = URLSession.shared.dataTask(with: imgURL!) { (data, response, error) in
                    DispatchQueue.main.async {
                        cell.coverImgView.image = UIImage(data: data!)
                    }
                }
                downloadTask.resume()
            }
        }
        return cell
    }
}
class MediaCollectionCell: UICollectionViewCell {
    @IBOutlet weak var coverImgView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
}
